<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="1000px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './fixResident.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { createFixResident, updateFixResident } from '/@/api/opms/fixResident';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';
  import { useUserStore } from '/@/store/modules/user';
  import { getOpmsFixFamilyInfoList } from '/@/api/opms/opmsFixFamilyInfo';
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const { createMessage } = useMessage();
  const { isAdmin, isAudit, isUser, userInfo } = useUserStore();

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    } else {
      if (isUser) {
        const dataTemp = await getOpmsFixFamilyInfoList({ userId: userInfo?.userId });
        const dataFamily = {
          hkType: dataTemp[0].hkType,
          groupNumber: dataTemp[0].groupNumber,
          hkbNumber: dataTemp[0].hkbNumber,
          householder: dataTemp[0].householder,
          familyId: dataTemp[0].id,
        };
        setFieldsValue({
          ...dataFamily,
        });
        console.log('户主信息-->', data);
      }
    }
  });
  const getTitle = computed(() => (!unref(isUpdate) ? '新增居民管理' : '编辑居民管理'));
  async function handleSubmit() {
    try {
      const values = await validate();
      //处理日期格式 如果后台日期对象为LocalDate 转换后的为 YYYY-MM-DD ，但是前端的日期选择器是 YYYY-MM-DD hh:mm:ss,需要转换一下
      values['issuingDate'] = dayjs(values['issuingDate']).format('YYYY-MM-DD');
      values['birthDate'] = dayjs(values['birthDate']).format('YYYY-MM-DD');
      setDrawerProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        await updateFixResident(values);
        createMessage.success('更新成功');
      } else {
        await createFixResident(values);
        createMessage.success('创建成功');
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<script lang="ts">
  export default { name: 'FixResidentDrawer' };
</script>
